package com.fivefu.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.fivefu.core.exception.FfSqlAnalysisException;
import com.fivefu.core.pojo.FfSql;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @Author zhf
 * @Description
 * @Date 2021/3/12
 */
@Component
public class SqlHandlerChain implements InitializingBean {

    @Autowired
    private ApplicationContext applicationContext;

    List<SqlHandler> handlerList = new ArrayList<>();

    public void addHandler(SqlHandler sqlHandler) {

        this.handlerList.add(sqlHandler);
    }

    public void handler(JSONObject jsonObject, FfSql ffSql) throws FfSqlAnalysisException {
        for (SqlHandler sqlHandler : handlerList) {
            try {
                sqlHandler.dealSql(jsonObject, ffSql);
            }catch (Exception e){
                e.printStackTrace();
                return;
            }

        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, SqlHandler> beansOfType = applicationContext.getBeansOfType(SqlHandler.class);
        beansOfType.forEach((key, value) -> {
            addHandler(value);
        });
        //实现排序
        handlerList = handlerList.stream().sorted(Comparator.comparingInt(SqlHandler::order)).collect(Collectors.toList());

    }
}
